package us.team.openAnAppAtRandom;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;

import java.util.List;
import java.util.Random;

import us.team.openAnAppAtRandom.model.AppList;
import us.team.openAnAppAtRandom.model.AppItem;
import us.team.openAnAppAtRandom.util.AppListManager;

public class AppListsActivity extends AppCompatActivity {
    
    private AppListManager appListManager;
    private ListView listView;
    private AppListAdapter adapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_lists);
        
        appListManager = new AppListManager(this);
        
        Button btnAddList = findViewById(R.id.btn_add_list);
        btnAddList.setOnClickListener(v -> showAddListDialog());
        
        Button btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> finish());
        
        listView = findViewById(R.id.list_app_lists);
        adapter = new AppListAdapter();
        listView.setAdapter(adapter);
        
        listView.setOnItemClickListener((parent, view, position, id) -> {
            AppList selectedList = appListManager.getAppLists().get(position);
            Intent intent = new Intent(AppListsActivity.this, ListDetailActivity.class);
            intent.putExtra("list_position", position);
            startActivity(intent);
        });
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 重新初始化应用清单管理器，确保获取最新数据
        appListManager = new AppListManager(this);
        // 刷新列表数据
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }
    
    private void showAddListDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("创建新清单");
        
        final EditText input = new EditText(this);
        input.setHint("输入清单名称");
        builder.setView(input);
        
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String listName = input.getText().toString().trim();
                if (!listName.isEmpty()) {
                    AppList newList = new AppList(listName);
                    appListManager.addAppList(newList);
                    adapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(AppListsActivity.this, "清单名称不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        
        builder.show();
    }
    
    /**
     * 显示删除清单确认对话框
     */
    private void showDeleteConfirmDialog(final int position, String listName) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("删除清单");
        builder.setMessage("确定要删除清单 \"" + listName + "\" 吗？此操作不可恢复。");
        
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 删除清单
                appListManager.removeAppList(position);
                adapter.notifyDataSetChanged();
                Toast.makeText(AppListsActivity.this, "清单已删除", Toast.LENGTH_SHORT).show();
            }
        });
        
        builder.setNegativeButton("取消", null);
        builder.show();
    }
    
    private void showConfirmationDialog(final String appName, final String packageName) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(appName);
        builder.setMessage("？");
        
        final AlertDialog dialog = builder.create();
        
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认(3秒)", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                openApp(packageName);
            }
        });
        
        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "换一个", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                dialog.dismiss();
                // 找到当前应用所在的清单
                for (int i = 0; i < appListManager.getAppLists().size(); i++) {
                    AppList list = appListManager.getAppLists().get(i);
                    if (list.size() > 0) {
                        int randomIndex = new Random().nextInt(list.size());
                        AppItem selectedApp = list.getApps().get(randomIndex);
                        showConfirmationDialog(selectedApp.getAppName(), selectedApp.getPackageName());
                        break;
                    }
                }
            }
        });
        
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                dialog.dismiss();
            }
        });
        
        dialog.show();
    }
    
    private void openApp(String packageName) {
        PackageManager pm = getPackageManager();
        Intent intent = pm.getLaunchIntentForPackage(packageName);
        if (intent != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, "无法打开应用", Toast.LENGTH_SHORT).show();
        }
    }
    
    private class AppListAdapter extends BaseAdapter {
        
        @Override
        public int getCount() {
            return appListManager.getAppLists().size();
        }
        
        @Override
        public Object getItem(int position) {
            return appListManager.getAppLists().get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.item_app_list, parent, false);
            }
            
            final AppList appList = appListManager.getAppLists().get(position);
            
            TextView tvListName = view.findViewById(R.id.tv_list_name);
            TextView tvAppCount = view.findViewById(R.id.tv_app_count);
            Button btnEditList = view.findViewById(R.id.btn_edit_list);
            
            tvListName.setText(appList.getName());
            tvAppCount.setText(appList.size() + " 个应用");
            
            btnEditList.setOnClickListener(v -> {
                // 打开清单详情页面进行管理
                Intent intent = new Intent(AppListsActivity.this, ListDetailActivity.class);
                intent.putExtra("list_position", position);
                startActivity(intent);
            });
            
            Button btnDeleteList = view.findViewById(R.id.btn_delete_list);
            btnDeleteList.setOnClickListener(v -> {
                // 显示删除确认对话框
                showDeleteConfirmDialog(position, appList.getName());
            });
            
            return view;
        }
    }
}